from typing import Union, Annotated

from fastapi import APIRouter, BackgroundTasks, Depends

router = APIRouter(prefix="/background-task", tags=["后台任务"])


# def write_notification(email: str, message=""):
#     with open("log.txt", mode="w") as email_file:
#         content = f"notification for {email}: {message}"
#         email_file.write(content)
async def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)


@router.post("/send-notification_1/{email}")
async def send_notification_1(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}


def write_log(message: str):
    with open("log.txt", mode="a") as log:
        log.write(message)


def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
    if q:
        message = f"found query: {q}\n"
        background_tasks.add_task(write_log, message)
    return q


@router.post("/send-notification_2/{email}")
async def send_notification_2(background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]):
    message = f"message to {q}\n"
    background_tasks.add_task(write_log, message)
    return {"message": "Message sent"}
